package com.kreao.korean.controller;

import com.kreao.korean.dto.ApiResponse;
import com.kreao.korean.dto.WordRequest;
import com.kreao.korean.dto.WordResponse;
import com.kreao.korean.entity.Word;
import com.kreao.korean.security.UserPrincipal;
import com.kreao.korean.service.WordServiceImpl;
import com.kreao.korean.service.interfaces.WordService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/words")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class WordController {
    
    private final WordService wordService;
    
    @PostMapping
    public ResponseEntity<?> createWord(
            @Valid @RequestBody WordRequest request,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            WordResponse word = wordService.createWord(request, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success("单词添加成功", word));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("单词添加失败: " + e.getMessage()));
        }
    }
    
    @PutMapping("/{wordId}")
    public ResponseEntity<?> updateWord(
            @PathVariable Long wordId,
            @Valid @RequestBody WordRequest request,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            WordResponse word = wordService.updateWord(wordId, request, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success("单词更新成功", word));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("单词更新失败: " + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{wordId}")
    public ResponseEntity<?> deleteWord(
            @PathVariable Long wordId,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            wordService.deleteWord(wordId, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success("单词删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("单词删除失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/{wordId}")
    public ResponseEntity<?> getWord(
            @PathVariable Long wordId,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            WordResponse word = wordService.getWord(wordId, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success(word));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取单词失败: " + e.getMessage()));
        }
    }
    
    @GetMapping
    public ResponseEntity<?> getUserWords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "createdAt") String sort,
            @RequestParam(defaultValue = "desc") String direction,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        
        Sort.Direction sortDirection = direction.equalsIgnoreCase("desc") ? 
            Sort.Direction.DESC : Sort.Direction.ASC;
        Pageable pageable = PageRequest.of(page, size, Sort.by(sortDirection, sort));
        
        Page<WordResponse> words = wordService.getUserWords(userPrincipal.getId(), pageable);
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @GetMapping("/search")
    public ResponseEntity<?> searchWords(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<WordResponse> words = wordService.searchWords(userPrincipal.getId(), keyword, pageable);
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @GetMapping("/category/{category}")
    public ResponseEntity<?> getWordsByCategory(
            @PathVariable Word.WordCategory category,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<WordResponse> words = wordService.getWordsByCategory(userPrincipal.getId(), category, pageable);
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @GetMapping("/favorites")
    public ResponseEntity<?> getFavoriteWords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<WordResponse> words = wordService.getFavoriteWords(userPrincipal.getId(), pageable);
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @GetMapping("/review")
    public ResponseEntity<?> getWordsForReview(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        List<WordResponse> words = wordService.getWordsForReview(userPrincipal.getId());
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @GetMapping("/need-review")
    public ResponseEntity<?> getWordsNeedReview(
            @RequestParam(defaultValue = "0.7") Double accuracy,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        List<WordResponse> words = wordService.getWordsNeedReview(userPrincipal.getId(), accuracy);
        return ResponseEntity.ok(ApiResponse.success(words));
    }
    
    @PostMapping("/{wordId}/favorite")
    public ResponseEntity<?> toggleFavorite(
            @PathVariable Long wordId,
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        try {
            WordResponse word = wordService.toggleFavorite(wordId, userPrincipal.getId());
            return ResponseEntity.ok(ApiResponse.success("收藏状态更新成功", word));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("更新收藏状态失败: " + e.getMessage()));
        }
    }
} 